﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Collections.ObjectModel;
using System.Linq.Expressions;
using System.Windows;
using System.Windows.Threading;
using XYAC.Framework.MonitorTireMaterialManual.Entities;
using XYAC.Framework.MonitorTireMaterialManual.Extensions;
using XYAC.Framework.MonitorTireMaterialManual.IServices;
using XYAC.Framework.MonitorTireMaterialManual.Views;

namespace XYAC.Framework.MonitorTireMaterialManual.ViewModels
{
    public partial class QualityDataHistoryViewModel : ViewModelBase
    {
        public QualityDataHistoryViewModel(IOptionsMonitor<AppConfig> options, ILogger<QualityDataHistoryViewModel> logger, IServiceProvider provider)
        {

            this.CurrentAppConfig = options;
            this.Logger = logger;
            this.provider = provider;
            //LoadCurrentSelectionSpecInfo();
            RefershLocalRecords();
            RefershTimer = new System.Timers.Timer();
            RefershTimer.Interval = 10 * 1000;
            RefershTimer.Elapsed += RefershTimer_Elapsed;
            RefershTimer.Start();
        }

        private void RefershTimer_Elapsed(object? sender, System.Timers.ElapsedEventArgs e)
        {
            RefershLocalRecords();

        }

        public System.Timers.Timer RefershTimer { get; set; }
        public IOptionsMonitor<AppConfig> CurrentAppConfig { get; }
        public ILogger<QualityDataHistoryViewModel> Logger { get; }

        private IServiceProvider provider;
        [ObservableProperty]
        private ObservableCollection<string> _querySpecComboSource;
        /// <summary>
        /// 本地数据总量
        /// </summary>
        [ObservableProperty]
        private int _totalLocalDataPage1Count;
        [ObservableProperty]
        private int _totalLocalDataPage1Index = 1;
        [ObservableProperty]
        private int _totalLocalDataPage2Count;
        [ObservableProperty]
        private int _totalLocalDataPage2Index = 1;
        [ObservableProperty]
        private int _totalLocalDataPage3Count;
        [ObservableProperty]
        private int _totalLocalDataPage3Index = 1;
        [ObservableProperty]
        private int _totalLocalDataPage4Count;
        [ObservableProperty]
        private int _totalLocalDataPage4Index = 1;
        /// <summary>
        /// 表格数据源
        /// </summary>
        [ObservableProperty]
        private IEnumerable<SemiSteelTreadScanReport> _semiSteelTreadScanReports;
        [ObservableProperty]
        private IEnumerable<SemiSteelSideInspectionReport> _semiSteelSideInspectionReports;
        [ObservableProperty]
        private IEnumerable<SemiSteelTriangleRubberReport> _semiSteelTriangleRubberReports;
        [ObservableProperty]
        private IEnumerable<PreCheckReport> _preCheckReports;

        /// <summary>
        /// 条件查询
        /// </summary>
        [ObservableProperty]
        public string _userChoiceQuerySpec;
        /// <summary>
        /// 是否为条件查询
        /// </summary>
        [ObservableProperty]
        public bool _chkAutoStartIsChecked = AutoStartupHelper.IsAutoStartupEnabled();
        /// <summary>
        /// 查询结束时间
        /// </summary>
        [ObservableProperty]
        public DateTimeOffset? _endDatePickerSelectedDate = DateTimeOffset.Now.AddDays(1);
        /// <summary>
        /// 查询开始时间
        /// </summary>
        [ObservableProperty]
        public DateTimeOffset? _startDatePickerSelectedDate = DateTimeOffset.Now.AddDays(-1);

        /// <summary>
        /// 刷新数据
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        private IEnumerable<TType> RefershLocalRecordsDetails<TType>(int pageIndex = -1, int pageSize = 20) where TType : ReportEntityBase, new()
        {
            try
            {
                using (var scope = this.provider.CreateScope())
                {
                    var service = scope.ServiceProvider.GetService<ILocalReportService>();
                    var data = service.GetPage<TType>(pageIndex, pageSize, orderConditions:
                              new List<(Expression<Func<TType, object>> KeySelector, bool Descending)>()
                              {
                                    new(T=>T.ID,true)//使用ID逆序排序
                              });

                    return data;
                }
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex.Message, ex);
                return Enumerable.Empty<TType>();
            }
        }

        [ObservableProperty]
        private int _userSelectDataType;

        [RelayCommand]
        public void QueryLocalDataHistory()
        {
            //if (this.ChkAutoStartIsChecked == true)
            //{
            //    RefershLocalRecordsViaConditions(this.TotalLocalDataPageIndex, 20);
            //    InitializeRecordSpec();
            //}
            //else
            //{

            //}
            RefershLocalRecords(20);
        }

        internal void RefershLocalRecords(int pageCount = 20)
        {
            try
            {

                if (this.UserSelectDataType == 0)//胎面
                {
                    this.TotalLocalDataPage1Count = GetPageCount<SemiSteelTreadScanReport>(pageCount);
                    var data = RefershLocalRecordsDetails<SemiSteelTreadScanReport>(this.TotalLocalDataPage1Index - 1, pageCount);
                    this.SemiSteelTreadScanReports = data;
                    this.PageValue1 = (uint)this.TotalLocalDataPage1Index;
                }
                else if (this.UserSelectDataType == 1)//胎侧
                {
                    this.TotalLocalDataPage2Count = GetPageCount<SemiSteelSideInspectionReport>(pageCount);
                    var data = RefershLocalRecordsDetails<SemiSteelSideInspectionReport>(this.TotalLocalDataPage2Index - 1, pageCount);
                    this.SemiSteelSideInspectionReports = data;
                    this.PageValue2 = (uint)this.TotalLocalDataPage2Index;

                }
                else if (this.UserSelectDataType == 2)//三角胶
                {
                    this.TotalLocalDataPage3Count = GetPageCount<SemiSteelTriangleRubberReport>(pageCount);
                    var data = RefershLocalRecordsDetails<SemiSteelTriangleRubberReport>(this.TotalLocalDataPage3Index - 1, pageCount);
                    this.SemiSteelTriangleRubberReports = data;

                    this.PageValue3 = (uint)this.TotalLocalDataPage3Index;
                }
                else if (this.UserSelectDataType == 3)//标准块
                {
                    this.TotalLocalDataPage4Count = GetPageCount<PreCheckReport>(pageCount);
                    var data = RefershLocalRecordsDetails<PreCheckReport>(this.TotalLocalDataPage4Index - 1, pageCount);
                    this.PreCheckReports = data;

                    this.PageValue4 = (uint)this.TotalLocalDataPage4Index;
                }
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex.Message, ex);
                MessageBox.Show($"查询本地检测记录失败:{ex.Message}", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);

            }
        }
        private int GetPageCount<TType>(int pageSize = 20) where TType : ReportEntityBase, new()
        {
            try
            {
                using (var scope = this.provider.CreateScope())
                {
                    var service = scope.ServiceProvider.GetService<ILocalReportService>();
                    var data = Math.Ceiling(service.GetCount<TType>() / (double)pageSize);

                    return (int)data;


                }
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex.Message, ex);
                return 0;
            }
        }

        /// <summary>
        /// 初始化同步记录下拉数据
        /// </summary>
        private void InitializeRecordSpec()
        {
            try
            {
                //拉取不同数据的类型
            }
            catch (Exception ex)
            {
                Logger?.LogError("初始化同步记录失败", ex);
            }
        }


        /// <summary>
        /// 上一页
        /// </summary>
        [RelayCommand]
        public void LocalDataNextPage()
        {


            if (this.UserSelectDataType == 0)//胎面
            {


                if (this.TotalLocalDataPage1Index + 1 > TotalLocalDataPage1Count)
                {
                    this.TotalLocalDataPage1Index = TotalLocalDataPage1Count;
                }
                else
                {
                    this.TotalLocalDataPage1Index++;
                }
            }
            else if (this.UserSelectDataType == 1)//胎侧
            {
                if (this.TotalLocalDataPage2Index + 1 > TotalLocalDataPage2Count)
                {
                    this.TotalLocalDataPage2Index = TotalLocalDataPage2Count;
                }
                else
                {
                    this.TotalLocalDataPage2Index++;
                }

            }
            else if (this.UserSelectDataType == 2)//三角胶
            {
                if (this.TotalLocalDataPage3Index + 1 > TotalLocalDataPage3Count)
                {
                    this.TotalLocalDataPage3Index = TotalLocalDataPage3Count;
                }
                else
                {
                    this.TotalLocalDataPage3Index++;
                }
            }
            else if (this.UserSelectDataType == 3)//标准块
            {
                if (this.TotalLocalDataPage4Index + 1 > TotalLocalDataPage4Count)
                {
                    this.TotalLocalDataPage4Index = TotalLocalDataPage4Count;
                }
                else
                {
                    this.TotalLocalDataPage4Index++;
                }
            }

            RefershLocalRecords();

        }
        /// <summary>
        /// 下一页
        /// </summary>
        [RelayCommand]
        public void LocalDataForwardPage()
        {
            if (this.UserSelectDataType == 0)//胎面
            {

                if (this.TotalLocalDataPage1Index - 1 <= 0)
                {
                    this.TotalLocalDataPage1Index = 1;
                }
                else
                {
                    this.TotalLocalDataPage1Index--;
                }
            }
            else if (this.UserSelectDataType == 1)//胎侧
            {
                if (this.TotalLocalDataPage2Index - 1 <= 0)
                {
                    this.TotalLocalDataPage2Index = 1;
                }
                else
                {
                    this.TotalLocalDataPage2Index--;
                }

            }
            else if (this.UserSelectDataType == 2)//三角胶
            {
                if (this.TotalLocalDataPage3Index - 1 <= 0)
                {
                    this.TotalLocalDataPage3Index = 1;
                }
                else
                {
                    this.TotalLocalDataPage3Index--;
                }

            }
            else if (this.UserSelectDataType == 3)//标准块
            {
                if (this.TotalLocalDataPage4Index - 1 <= 0)
                {
                    this.TotalLocalDataPage4Index = 1;
                }
                else
                {
                    this.TotalLocalDataPage4Index--;
                }

            }
            RefershLocalRecords();
        }

        [RelayCommand]
        private void ViewReport(ReportEntityBase report)
        {
            Dispatcher.CurrentDispatcher.Invoke(() =>
            {

                if (report is SemiSteelSideInspectionReport vm)
                {
                    //var view = this.provider.GetService<SemiSteelSideInspectionReadonlyView>();
                    var view = this.provider.GetService<SemiSteelSideInspectionView2>();
                    view.ClearViewModelValue();
                    view.setMode(true);
                    view.ViewModel.SemiSteelSideInspectionReport = vm;
                    var Window = new Window();
                    Window.Title = "胎侧检测结果查看";
                    Window.Content = view;
                    Window.Width = 800;
                    Window.Height = 820;
                    Window.ResizeMode = ResizeMode.NoResize;
                    Window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                    //Window.WindowState = WindowState.Maximized;
                    var result = Window.ShowDialog();
                }
                else if (report is SemiSteelTriangleRubberReport vm1)
                {
                    //var view = this.provider.GetService<SemiSteelTriangleRubberReadonlyView>();
                    //var view = this.provider.GetService<SemiSteelTriangleRubberView1>();
                    var view = this.provider.GetService<SemiSteelTriangleRubberView2>();
                    view.ClearViewModelValue();
                    view.setMode(true);
                    view.ViewModel.SemiSteelTriangleRubberReport = vm1;
                    var Window = new Window();
                    Window.Title = "三角胶检测结果查看";
                    Window.Content = view;
                    Window.Width = 750;
                    Window.Height = 600;
                    Window.ResizeMode = ResizeMode.NoResize;
                    Window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                    //Window.WindowState = WindowState.Maximized;
                    var result = Window.ShowDialog();
                }
                else if (report is SemiSteelTreadScanReport vm2)
                {
                    //var view = this.provider.GetService<SemiSteelTreadScanReadonlyView>();
                    var view = this.provider.GetService<SemiSteelTreadScanView2>();
                    view.ClearViewModelValue();
                    view.setMode(true);
                    view.ViewModel.SemiSteelTreadScanReport = vm2;
                    var Window = new Window();
                    Window.Title = "胎面检测结果查看";
                    Window.Content = view;
                    Window.Width = 800;
                    Window.Height = 820;
                    Window.ResizeMode = ResizeMode.NoResize;
                    Window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                    //Window.WindowState = WindowState.Maximized;
                    var result = Window.ShowDialog();
                }
                else if (report is PreCheckReport vm3)
                {
                    //var view = this.provider.GetService<SemiSteelTreadScanReadonlyView>();
                    var view = this.provider.GetService<PreCheckView2>();
                    view.ClearViewModelValue();
                    view.setMode(true);
                    view.ViewModel.PreCheckReport = vm3;
                    view.ViewModel.IsReadonly= true;
                    var Window = new Window();
                    Window.Title = "标准块检测结果查看";
                    Window.Content = view;
                    Window.Width = 800;
                    Window.Height = 700;
                    Window.ResizeMode = ResizeMode.NoResize;
                    Window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                    var result = Window.ShowDialog();
                }
            });

        }

        [RelayCommand]
        private void GoToFirstPage()
        {
            if (this.UserSelectDataType == 0)//胎面
            {


                this.TotalLocalDataPage1Index = 1;
            }
            else if (this.UserSelectDataType == 1)//胎侧
            {

                this.TotalLocalDataPage2Index = 1;

            }
            else if (this.UserSelectDataType == 2)//选择类型
            {

                this.TotalLocalDataPage3Index = 1;

            }

            RefershLocalRecords();
        }
        private void GoToLastPage()
        {
            if (this.UserSelectDataType == 0)//胎面
            {


                this.TotalLocalDataPage1Index = TotalLocalDataPage1Count;
            }
            else if (this.UserSelectDataType == 1)//胎侧
            {

                this.TotalLocalDataPage2Index = TotalLocalDataPage2Count;

            }
            else if (this.UserSelectDataType == 2)//选择类型
            {

                this.TotalLocalDataPage3Index = TotalLocalDataPage3Count;

            }

            RefershLocalRecords();
        }

        [ObservableProperty]
        private uint _pageValue1;
        [ObservableProperty]
        private uint _pageValue2;
        [ObservableProperty]
        private uint _pageValue3;
        [ObservableProperty]
        private uint _pageValue4;
        [RelayCommand]
        private void PageChanged()
        {
            if (this.UserSelectDataType == 0)//胎面
            {


                this.TotalLocalDataPage1Index = (int)this.PageValue1;
            }
            else if (this.UserSelectDataType == 1)//胎侧
            {

                this.TotalLocalDataPage2Index = (int)this.PageValue2;

            }
            else if (this.UserSelectDataType == 2)//选择类型
            {

                this.TotalLocalDataPage3Index = (int)this.PageValue3;

            }

            RefershLocalRecords();
        }
    }
}
